<?php

namespace app\api\controller;

use addons\recharge\model\MoneyLog;
use app\common\controller\Api;
use addons\third\model\Third;
use addons\recharge\model\Order as OrderModel;
use app\common\model\User;
use EasyWeChat\Factory as WXPAY_APP;
use think\Db;

/**
 * 充值
 */
class Recharge extends Api
{
    protected $noNeedLogin = ['callback_for_wxapp'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->model = new OrderModel;

    }

    /**
     * 充值余额
     * @return string
     */
    public function recharge()
    {
        $this->success('',$this->leve_recharge());
    }

    private function leve_recharge()
    {
        $list = db('vip')->field('id,type,introduction,price')->select();
        foreach($list as &$v){
            $v['type'] = db('category')->where('id',$v['type'])->value('name');
        }
        return $list;
    } 

    /**
     * 余额日志
     * @return string
     */
    public function moneylog()
    {
        $moneyloglist = MoneyLog::where(['user_id' => $this->auth->id])
            ->order('id desc')
            ->paginate(10);

        $this->view->assign('title', __('Balance log'));
        $this->view->assign('moneyloglist', $moneyloglist);
        return $this->view->fetch();
    }

    /**
     * 创建订单并发起支付请求
     * @throws \think\exception\DbException
     */
    public function submit()
    {   
        $vip_id = $this->request->request('vip_id',2);
        $count = db('vip_log')->where(['user_id' => $this->auth->id])->where('end_time','>',time())->count();
        if($count){
            $this->error('当前套餐还没到期,不可再次充值');
        }

        $vip = db('vip')->where('id',$vip_id)->find();
        $money = $vip['price'];
        
         // 创建订单
        if ($this->model->order_add($this->user_id, $money,1,$vip_id)) {
            // 发起微信支付
            $this->init_wx_pay_for_wxapp();
            $this->make_wx_pay('wxapp');
            
        }
        $error = $this->model->getError() ?: '订单创建失败';
        return $this->error($error);
    }

    private function init_wx_pay_for_wxapp(){
        $config = get_addon_config('litestore');
        $options = [
            'debug' => true,
            'log' => [
                'level' => 'debug',
                'file' => '/tmp/easywechat.log',
            ],
            'app_id' => $config['AppID'],
            'mch_id' => $config['MCHID'],
            'key' => $config['APIKEY'],
            'notify_url' => \think\Request::instance()->domain().'/api/recharge/callback_for_wxapp',

        ];
        $this->wxapp = WXPAY_APP::payment($options);
    }

    private function make_wx_pay($platform){
    	$third = Third::where(['user_id' => $this->user_id, 'platform' => $platform])->find();
        $payment = $this->wxapp;

        $attributes = [
		    'trade_type'       => 'JSAPI',
		    'body'             => $this->model['order_no'],
		    'detail'           => 'OrderID:'.$this->model['id'],
		    'out_trade_no'     => $this->model['order_no'],
		    //'total_fee'        => $this->model['pay_price'] * 100, // 单位：分
            'total_fee'        => 1, // 单位：分
		    'openid'           => $third['openid'],
		];
        $result = $payment->order->unify($attributes);
		if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $prepayId = $result['prepay_id'];
            $config = $payment->jssdk->sdkConfig($prepayId);
			return $this->success('预支付成功',$config);
		}
		return $this->error('微信支付调用失败',$result);
    }


    public function callback_for_wxapp(){

        // $message['out_trade_no'] = '2021050454575749';
        // $message['transaction_id'] = '4200000993202103231704538818';
        // $message['total_fee'] = '1';

        // $order = $this->model->payDetail($message['out_trade_no']);
        // $order->updatePayStatus($message['transaction_id'],$message['total_fee']);

        $this->init_wx_pay_for_wxapp();
        $response = $this->wxapp->handlePaidNotify(function ($message, $fail) {
            $order = $this->model->payDetail($message['out_trade_no']);
            // Log::record($message,'message');
            // Log::record($order,'order');
            if (empty($order)) { // 如果订单不存在
                return true;
                //return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code']=== 'SUCCESS') {
                    $order->updatePayStatus($message['transaction_id'],$message['total_fee']);
                }
            }

            return true; // 返回处理完成
        });

        $response->send();
    }

    // 充值类型
    public function recharge_type()
    {

        $recharge_type = db('category')->field('id,name')->where('type','vip')->select();
        $this->success('成功',$recharge_type);
        
    }
    // 实体卡充值
    public function entity_recharge()
    {
        
        $card_number = $this->request->request('card_number');
        $password = $this->request->request('password');

        if(!$card_number){
            $this->error('卡号不能为空');
        }

        if(!$password){
            $this->error('密码不能为空');
        }

        // 启动事务
        Db::startTrans();
        try {


            $entity_model = new \app\admin\model\EntityCards;
            $entity = $entity_model->where(['card_number' => $card_number,'password' => $password])->find();
            if(!$entity){
                throw new \Exception("输入的卡号或密码不正确");
            }
            if($entity->status != 1){
                throw new \Exception("已失效");
            }

            
            $count = db('vip_log')->where(['user_id' => $this->auth->id])->where('end_time','>',time())->count();

            if($count){
                throw new \Exception("当前套餐还没到期,不可再次充值");
            }
            $entity->status = 2;
            $entity->user_id = $this->auth->id;
            $entity->nickname = $this->auth->nickname;
            $entity->save();

            
    
            $vip_log_model = new \app\admin\model\VipLog;
            $type_name = db('category')->field('id,name')->where('id',$entity->type)->value('name');
    
            $vip = db('vip')->where(['type' => $entity->type])->find();
            $vip_log = $vip;
            unset($vip_log['id']);
            $vip_log['user_id'] = $entity->user_id;
            $vip_log['nickname'] = $entity->nickname;
            $vip_log['type_name'] = $type_name;
            $vip_log['used_service_number'] = $vip['service_number'];
            $vip_log['end_time'] = strtotime('+1 year');
            $vip_log_model->allowField(true)->save($vip_log);

            $user = User::get($entity->user_id);
            $user->level_time = strtotime('+1 year');
            $user->level  = 1;
            $user->save();

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
            // 回滚事务
            Db::rollback();
        }
        $this->success('充值成功');

    }

    // 我的会员卡
    public function entity_index()
    {

        $vip_log_model = new \app\admin\model\VipLog;
        $row = $vip_log_model->field('type_name,service_number,used_service_number,introduction,end_time')->where('user_id',$this->auth->id)->where('end_time','>',time())->find();
        $row = $row ?? '';
        $this->success('',$row);
        
    }


}
